package servlets;

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ejbSessions.ManagerAbilitaRemote;

/**
 * Servlet implementation class InoltraRichiestaAbilita
 */
public class InoltraRichiestaAbilita extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InoltraRichiestaAbilita() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request, response);
	}
	
	private void gestisciRichiesta(HttpServletRequest request, HttpServletResponse response){
		int idUtente;
		try{
			Hashtable<String,String> env = new Hashtable<String,String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL,"localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			Object ref = jndiContext.lookup("ManagerAbilita/remote");
			ManagerAbilitaRemote managerAbilita = (ManagerAbilitaRemote)ref;
			
			idUtente = (Integer) request.getSession().getAttribute("userid");
			
			String nome,descrizione;
			nome = request.getParameter("nome");
			descrizione = request.getParameter("descrizione");
			managerAbilita.nuovaRichiestaAbilitaUtente(idUtente, nome, descrizione);
			String messaggio = "Richiesta per abilita': "+nome+" inoltrata.";
			request.getSession().setAttribute("messaggio", messaggio);
		}catch (Exception e) {
			e.printStackTrace();
		}
		try{
			response.sendRedirect("./InterazioneAdmin");
		}catch (Exception e) {
			e.printStackTrace();
		}
	}	

}
